<template>
  <div class="app-container">
    <myprocess-detail v-if="$store.state.mobile.userAgent ==='mobile'"></myprocess-detail>
    <div v-else  style='position: relative'>
      <el-tabs type="border-card" @tab-click="handleClick" v-model="activeName">
        <el-tab-pane label="基本信息" v-loading="tasksLoad" name="first">
          <!-- 审批信息 -->
          <el-card class="box-card" v-loading="processInstanceLoading" v-for="(item, index) in runningTasks" :key="index" v-if="details != 'details'">
            <div slot="header" class="clearfix">
              <span class="el-icon-picture-outline">审批任务【{{ item.name }}】</span>
            </div>
            <el-col :span="16" :offset="6" >
              <el-form :ref="'form' + index" :model="auditForms[index]" :rules="auditRule" label-width="100px">
                <el-form-item label="流程名" v-if="processInstance && processInstance.name">
                  {{ processInstance.name }}
                </el-form-item>
                <!-- <el-form-item label="流程发起人" v-if="processInstance && processInstance.startUser">
                  {{ processInstance.startUser.nickname }}
                  <el-tag type="info" size="mini">{{ processInstance.startUser.deptName }}</el-tag>
                </el-form-item> -->
                <el-form-item label="审批建议" prop="reason">
                  <el-input type="textarea" v-model="auditForms[index].reason" placeholder="请输入审批建议" />
                </el-form-item>
                 <el-form-item  prop="isCC" v-if="carbonFlag">
                  <el-checkbox v-model="checked" @change="handleCheckedChange">是否抄送</el-checkbox>
                </el-form-item>
                <el-form-item label="抄送给" prop="cc" v-if="checked" class="ruleInput">
                    <div class="selectStyle">
                        <div class="inputSelect" :style="{'border': showFlag ? '1px solid #ff4949' : '1px solid #DCDFE6'}">
                            <el-tag
                                v-for="tag in tagsList"
                                :key="tag.id">
                                {{ tag.username }}
                            </el-tag>
                        </div>
                        <el-button  type="primary" @click="onRecipient" style="height: 36px">选择</el-button>
                    </div>
                    <div class="noNull" v-if="showFlag">抄送不能为空</div>
                </el-form-item>
                <el-form-item label="附加信息" prop="info" v-if="infoFlag">
                  <span slot="label">
                    <span class="span-box">
                      <span>附加信息</span>
                      <el-tooltip effect="dark" content="最多上传五个文件，单个大小不超过2M，支持word、excel、pdf、txt、png、jpg、jpeg、tiff、bmp格式文件" placement="top">
                        <i class="el-icon-question" ></i>
                      </el-tooltip>
                    </span>
                  </span>
                   <el-upload
                        class="upload-demo"
                        :before-upload="beforeUpload"
                        :on-success="uploadSuccess"
                        :limit="5"
                        ref="uploadFile"
                        :multiple="true"
                        :on-exceed="onExceed"
                        :headers="{ 'Authorization': 'Bearer ' + localStorageTemp, 'tenant-id': tenantId }"
                        :show-file-list="false"
                        :action="loadAction">
                        <el-button  type="primary" style="width: 200px" v-loading="uploadLoading">文件上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            <div v-if="fileDocList.length > 0" class="showFileDoc">
                                <div class="lineFilecss" v-for="(item, idx) in fileDocList" :key="idx">
                                    <i class="el-icon-document"></i>
                                    <span class="fileTextCss" :title="item.name" @click="viewFile(item)">{{item.name}}</span>
                                    <span><i class="el-icon-download fileIcon" @click="downloadFileFunc(item)"></i></span>
                                    <span><i class="el-icon-delete fileIcon" @click="deleteFile(item, idx)"></i></span>
                                </div>
                            </div>
                        </div>
                    </el-upload>
                </el-form-item>
              </el-form>
              <div style="margin-left: 10%; margin-bottom: 20px; font-size: 14px;">
                <el-button  v-if="buttonList.filter((_) => _.value == 'flow_agree') && buttonList.filter((_) => _.value == 'flow_agree').length == 1" icon="el-icon-edit-outline" type="success" size="mini" @click="handleAudit(item, true)">
                  {{buttonList.filter((_) => _.value == 'flow_agree') && buttonList.filter((_) => _.value == 'flow_agree')[0].label}}
                </el-button>
                <el-button  v-if="buttonList.filter((_) => _.value == 'flow_not_agree') && buttonList.filter((_) => _.value == 'flow_not_agree').length == 1 && !exchangeobj.manager_id && !exchangeobj.newMenuId" icon="el-icon-circle-close" type="danger" size="mini" @click="handleAudit(item, false)">
                  {{buttonList.filter((_) => _.value == 'flow_not_agree') && buttonList.filter((_) => _.value == 'flow_not_agree')[0].label}}
                </el-button>
                <el-button  v-if="buttonList.filter((_) => _.value == 'flow_translate') && buttonList.filter((_) => _.value == 'flow_translate').length == 1" icon="el-icon-edit-outline" type="primary" size="mini" @click="handleUpdateAssignee(item)">
                  {{buttonList.filter((_) => _.value == 'flow_translate') && buttonList.filter((_) => _.value == 'flow_translate')[0].label}}
                </el-button>
                <!-- <el-button  icon="el-icon-edit-outline" type="primary" size="mini" @click="handleDelegate(item)">委派</el-button> -->
                <el-button  v-if="buttonList.filter((_) => _.value == 'flow_reject') && buttonList.filter((_) => _.value == 'flow_reject').length == 1" icon="el-icon-refresh-left" type="warning" size="mini" @click="handleBack(item)">
                  {{buttonList.filter((_) => _.value == 'flow_reject') && buttonList.filter((_) => _.value == 'flow_reject')[0].label}}
                </el-button>
              </div>
            </el-col>
          </el-card>
          <!-- 申请信息 -->
          <el-card v-if="idList && idList.length > 0" v-loading="processInstanceLoading">
              <el-tabs v-model="activeNameList"   tab-position="top" @tab-click="handleClickInfo">
                <template v-if="exchangeMenuShow">
                  <el-tab-pane :label="'申请信息【' + processInstance.name + '】'" :name="index.toString()" v-for="(item, index) in exchangeOriginData" :key="index" >
                    <div v-loading="processInstanceLoadingExchange" style="min-height:400px;" v-if="showexchange">
                      <exchangeMenuParser tableName="" :originData="item" status="view"></exchangeMenuParser>
                    </div>
                     <!-- <parser :key="timekey" :form-conf="item" :originData="originData" :status="'view'" @submit="submitForm" v-if="!exchangeMenuShow && showForm"/> -->
                 </el-tab-pane>
                 </template>
                <template v-else>
                  <el-tab-pane :label="'申请信息【' + processInstance.name + '】'" :name="index.toString()" v-for="(item, index) in dataList" :key="index" >
					          <parser :key="timekey" :codeReshow="codeReshow" :form-conf="item" :originData="originData" :status="'view'" @submit="submitForm" v-if="showForm"/>
                  </el-tab-pane>
                </template>
              </el-tabs>
          </el-card>
          <el-card class="box-card" v-loading="processInstanceLoading" v-else>
            <div slot="header" class="clearfix">
              <span class="el-icon-document">申请信息【{{ processInstance.name }}】</span>
            </div>
            <el-col :span="16" :offset="6">
              <div >
                <!-- <parser :key="new Date().getTime()" :form-conf="detailForm" @submit="submitForm" /> -->
                <div v-loading="processInstanceLoadingExchange" style="min-height:400px;" v-if="showexchange">
                  <exchangeMenuParser v-if="exchangeMenuShow" tableName="" :originData="exchangeOriginData[0]" status="view"></exchangeMenuParser>
                </div>
                <parser v-if="!exchangeMenuShow" ref="parserRef" :codeReshow="codeReshow" :key="timekey" :form-conf="detailForm" :originData="originData" :status="'view'" @submit="submitForm"/>
              </div>
            </el-col>
            <!-- <div v-if="this.processInstance.processDefinition && this.processInstance.processDefinition.formType === 20">
              <router-link :to="this.processInstance.processDefinition.formCustomViewPath + '?id='
                                + this.processInstance.businessKey">
                <el-button type="primary">点击查看</el-button>
              </router-link>
            </div> -->
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="流转记录" v-loading="tasksLoad" name="second">
          <el-col :span="16" :offset="4" >
            <div class="block">
              <el-timeline>
                <el-timeline-item v-for="(item, index) in tasks" :key="index"
                                  :icon="getTimelineItemIcon(item)" :type="getTimelineItemType(item)">
                  <p style="font-weight: 700">任务：{{ item.name }}</p>
                  <el-card :body-style="{ padding: '10px' }">
                    <label v-if="item.assigneeUser" style="font-weight: normal; margin-right: 30px;">
                      审批人：{{ item.assigneeUser.nickname }}
                     <el-tag type="info" size="mini" v-if="item.assigneeUser.deptName">{{ item.assigneeUser.deptName }}</el-tag>
                    </label>
                    <label style="font-weight: normal">创建时间：</label>
                    <label style="color:#8a909c; font-weight: normal">{{ parseTime(item.createTime) }}</label>
                    <label v-if="item.endTime" style="margin-left: 30px;font-weight: normal">审批时间：</label>
                    <label v-if="item.endTime" style="color:#8a909c;font-weight: normal"> {{ parseTime(item.endTime) }}</label>
                    <label v-if="item.durationInMillis" style="margin-left: 30px;font-weight: normal">耗时：</label>
                    <label v-if="item.durationInMillis" style="color:#8a909c;font-weight: normal"> {{ getDateStar(item.durationInMillis) }} </label>
                    <!-- <p v-if="item.reason">
                      <el-tag :type="getTimelineItemType(item)">{{ item.comment }}</el-tag>
                    </p> -->
                    <div style="margin-top: 10px;"  v-if="item.reason">
                      <span>审批意见：{{item.reason}}</span>
                    </div>
                    <div style="margin-top: 10px;"  v-if="item.fileList&&item.fileList.length > 0">
                      <span>附加信息：</span>
                      <div class="lineFilecss" v-for="(item, idx) in item.file" :key="idx">
                          <i class="el-icon-document"></i>
                          <span class="fileTextCss" :title="item.name" @click="viewFile(item)">{{item.name}}</span>
                          <span><i class="el-icon-download fileIcon" @click="downloadFileFunc(item)"></i></span>
                      </div>
                      <div style="display: flex">
                        <div  v-for="(item, index) in item.imageList" :key="index" style="margin-right: 20px;margin-top: 10px">
                             <el-image 
                                style="width: 100px; height: 100px"
                                :src="item.url" 
                                :preview-src-list="[item.url]"
                               >
                              </el-image>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-col>
        </el-tab-pane>
        <el-tab-pane label="流程跟踪" v-loading="processInstanceLoading" name="third">
          <my-process-viewer key="designer" v-model="bpmnXML" v-bind="bpmnControlForm" :activityData="activityList"
              :processInstanceData="processInstance" :taskData="tasks" :result="result"/>
        </el-tab-pane>
    </el-tabs>
     <el-button size='mini' style='position: absolute;right:10px;top:5px;' type="primary" @click="returnTale">返回</el-button>
    <!-- 对话框(转派审批人) -->
    <el-dialog title="转派审批人" :visible.sync="updateAssignee.open" width="500px" append-to-body>
      <el-form ref="updateAssigneeForm" :model="updateAssignee.form" :rules="updateAssignee.rules" label-width="110px">
        <el-form-item label="新审批人" prop="assigneeUserId">
          <el-select v-model="updateAssignee.form.assigneeUserId" clearable style="width: 100%">
            <el-option v-for="item in userOptions" :key="parseInt(item.id)" :label="item.nickname" :value="parseInt(item.id)" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateAssigneeForm">确 定</el-button>
        <el-button @click="cancelUpdateAssigneeForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 退回 -->
     <el-dialog title="驳回" :visible.sync="returnBtn.open" width="650px" append-to-body >
      <el-form ref="returnBtnForm" :model="returnBtn.form"  label-width="178px" :rules="returnBtn.rules">
        <el-form-item label="驳回方式"  prop="rejection">
          <el-radio-group v-model="returnBtn.form.rejection" @change="changeRejection">
            <el-radio :label="1" >驳回发起人</el-radio>
            <el-radio :label="2">驳回上一步</el-radio>
            <el-radio :label="3">驳回指定节点</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="返回方式" prop="returnMethod">
          <el-radio-group v-model="returnBtn.form.returnMethod">
            <el-radio :label="1">按流程图执行</el-radio>
            <!-- <el-radio :label="2" v-if="returnBtn.form.rejection !=3">回到本节点</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="驳回到节点（按流程图）" prop="distFlowElementId" v-if="returnBtn.form.rejection==3">
          <el-select v-model="returnBtn.form.distFlowElementId" clearable style="width: 100%">
            <el-option v-for="item in nodeList" :key="item.nodeId" :label="item.nodeName" :value="item.nodeId" />
          </el-select>
        </el-form-item>
         <!-- <el-form-item label="审批建议" prop="message">
           <el-input type="textarea" v-model="returnBtn.form.message"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelReturnBtnForm">取 消</el-button>
        <el-button type="primary" @click="submitReturnBtnForm">驳 回</el-button>
      </div>
    </el-dialog>
    <ChoiceUser  ref="getUser" @userInfo="info" :tagsList="tagsList"  v-if="openRecipient" @closeRecipient="closeRecipient"/>
    </div>
     </div>
</template>

<script>
import exchangeMenuParser from '@/components/exchangeMenuParser/index.vue'
import {getProcessDefinitionBpmnXML} from "@/api/bpm/definition";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import store from "@/store";
import {decodeFields} from "@/utils/formGenerator";
import Parser from '../../custom/formdesign/components/parser'
import {createProcessInstance, getProcessInstance} from "@/api/bpm/processInstance";
import {approveTask, getTaskListByProcessInstanceId, rejectTask, updateTaskAssignee,getNodeList,doBack,doBackDist,getBatchApprovalDetail,
  batchApprove, batchReject, batchAssignee,batchDoBackDist,batchCarbonCopy
  } from "@/api/bpm/task";
import {getDate} from "@/utils/dateUtils";
import {listSimpleUsers} from "@/api/system/user";
import {getActivityList,getCarbonCopy} from "@/api/bpm/activity";
import { updata,getChildListData} from "@/api/custom/formPoster";
import ChoiceUser from '@/components/selectUser/index.vue'
import myprocessDetail from '@/views/custom/mobiledesign/mobileComponents/myprocessDetail.vue'
// 下载插件
import { download } from '@/utils/index'
import { getAccessToken } from "@/utils/auth";
import { getListData,getAllListDataForm } from '../../../api/custom/formPoster'
const basicTypes = ['number', 'color', 'rate', 'date', 'time', 'password', 'textArea', 'input', 'slider','place', 'numbers']; //从数据库中获取值无需处理

// 流程实例的详情页，可用于审批
export default {
  name: "ProcessInstanceDetail",
  components: {
    Parser,
    ChoiceUser,
    myprocessDetail,
    exchangeMenuParser
  },
  data() {
    return {
      exchangeMenuShow:false,
      showexchange:false,
      exchangeOriginData:[],
      originData: {},
      activeNameList: "0",
      carbonFlag: false,
      infoFlag: false, //是否显示附加信息
      showFlag: false,
      checked: false,
      tagsList: [],
      openRecipient: false,
      activeName: 'first',
      details: '',
      editRow: '',
      toView: '', //关联流程 从表单管理页面 点击查看跳转到 流程详情
      // 遮罩层
      processInstanceLoading: true,
      // 流程实例
      id: undefined, // 流程实例的编号
      processInstance: {},
      userId: '',
      // 流程表单详情
      detailForm: {
        fields: []
      },

      // BPMN 数据
      bpmnXML: null,
      buttonList: [],
      bpmnControlForm: {
        prefix: "activiti"
      },
      activityList: [],

      // 审批记录
      tasksLoad: true,
      tasks: [],

      // 审批表单
      runningTasks: [],
      auditForms: [],
      auditRule: {
        reason: [{ required: true, message: "审批建议不能为空", trigger: "blur" }],
      },

      // 转派审批人
      userOptions: [],
      // 驳回到指定节点
      nodeList: [],
      updateAssignee: {
        open: false,
        form: {
          assigneeUserId: undefined,
        },
        rules: {
          assigneeUserId: [{ required: true, message: "新审批人不能为空", trigger: "change" }],
        }
      },
      // 退回
      returnBtn: {
        open: false,
        form: {
          rejection: 1,
          returnMethod: 1,
          distFlowElementId: undefined,
          // message: undefined
        },
        rules: {
          rejection: [{ required: true,  message: "驳回方式不能为空",trigger: "blur"}],
          returnMethod: [{ required: true, message: "返回方式不能为空", trigger: "blur"}],
          distFlowElementId: [{ required: true,  message: "节点不能为空", trigger: "blur"}],
          // message: [{ required: true,  message: "审批建议不能为空", trigger: "blur"}],
        }
      },
      // 数据字典
      categoryDictDatas: getDictDatas(DICT_TYPE.BPM_MODEL_CATEGORY),
      uploadLoading: false,
      fileDocList: [],
      loadAction: '',
      localStorageTemp: '',
      tenantId: '',
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址,
      headersImg: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      uploadImgLoading: false,
      fileList: [],
      imageList: [],
      uploadList: [],
      dataList: [],
      idListbyDetail: [],
      tableTagIconsMap: new Map(), // 子表单tag的map
      tagIconsMap: new Map(), // 普通组件tag map
      showForm: false,
      timekey:0,
      exchangeobj:{},
      processInstanceLoadingExchange:false
    };
  },
  watch: {
    tagsList: function(newData,oldData){
       if(newData.length > 0){
        this.showFlag = false
       }
    }
  },
  created() {
    this.api = process.env.VUE_APP_BASE_API;
    this.loadAction = `${this.api}/admin-api/infra/file/upload`;
    this.localStorageTemp = window.localStorage.getItem('ACCESS_TOKEN');
    this.tenantId = window.localStorage.getItem('TENANT_ID')
    this.details = this.$route.query.details
    this.toView = this.$route.query && this.$route.query.toView
    this.tableId = this.$route.query && this.$route.query.tableId
    this.versionId = this.$route.query && this.$route.query.versionId
    this.result = this.$route.query && this.$route.query.result
    this.formRecordIdList = this.$route.query && this.$route.query.formRecordIdList
    this.formRecordVersionList = this.$route.query && this.$route.query.formRecordVersionList
    this.editRow = this.$route.query.edit && JSON.parse(this.$route.query.edit)
    this.id = this.$route.query.id;
    this.idList = this.$route.query.idList
    if (!this.id) {
      this.$message.error('未传递 id 参数，无法查看流程信息');
      return;
    }
    this.getDetail();

    // 获得用户列表
    this.userOptions = [];
    listSimpleUsers().then(response => {
      this.userOptions.push(...response.data);
    });

  },
  methods: {
    returnTale() {
      this.$router.go(-1)
    },
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
    },
    // 图片删除
    handleRemove(file, fileList) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if(findex > -1) {
        this.fileList.splice(findex, 1);
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$message.warning('上传图片不能超过3个')
    },
    // 图片上传前回调
    handleBeforeUpload(file) {
        const size = file.size / 1024 / 1024
        if (size > 100) {
            this.$message.warning('图片最大不超过2M')
            return false
        }
        this.uploadImgLoading = true
    },
    // 图片上传
    handleUploadSuccess(res,file) {
      if(res.code == 0) {
        this.fileList.push({name: file.name, url: res.data})
      }else{
        this.$modal.msgError("上传图片失败，请重试");
      }
      this.uploadImgLoading = false
    },
    viewFile (item) {
        const nameSplitList = item.name.split('.')
        const type = nameSplitList[nameSplitList.length - 1]
        if (['jpeg', 'jpg', 'png'].includes(type)) {
            window.open(item.url, '_blank')
        } else {
            this.$message.warning('当前文件不支持预览')
        }
        // 代码注释
        //  else if (['docx', 'doc', 'xlsx', 'xls', 'pdf'].includes(type)) {
        //     this.$message.warning('当前文件不支持预览')
        //     // let newFileUrl = encodeURIComponent(item.url)
        //     // newFileUrl = 'http://view.xdocin.com/xdoc?_xdoc=' + newFileUrl
        //     // window.open(newFileUrl, '_blank')
        // } else if (type === 'pdf') {
        //     this.$message.warning('当前文件不支持预览')
        // }
    },
    downloadFileFunc (item) {
        download(item.url, item.name)
    },
    deleteFile (item, idx) {
        this.fileDocList.splice(idx, 1)
    },
    onExceed (files, fileList) {
        if (this.fileDocList.length === 5) {
            this.$message.warning('当前限制5个文件')
            // this.$refs.uploadFile.abort()
            return false
        }
    },
    // 上传前钩子判断
    beforeUpload (file) {
        const size = file.size / 1024 / 1024
        if (size > 10) {
            this.$message.warning('文件最大不超过1M')
            return false
        }
        this.uploadLoading = true
    },
    // 上传成功钩子事件
    uploadSuccess (response, file, fileList) {
        if (response.code === 0) {
            this.fileDocList.push({name: file.name, url: response.data})
        }else{
          this.$modal.msgError("上传文件失败，请重试");
        }
        this.uploadLoading = false
    },
    handleCheckedChange(val) { // 是否抄送  -- false  清空 tagsList
      if(!val){
        this.tagsList = []
      }
    },
    onRecipient() {
      this.openRecipient = true
    },
    info(data) {
      this.tagsList = data 
    },
     closeRecipient() {
      this.openRecipient = false
    },
    handleClick(tab, event) {
      if (tab.index == 2) {
          this.getDetail();
      }
    },
    async handleClickInfo(tab) {
        this.showForm = false
        const data =this.dataList[tab.index].fields
        const {panelType, childrenParams, parentParams, tableName} = this.$route.query
        const tempObj = {}
        tempObj.tableNames = []
          // 存储所有子表单的字段name
        const fieldNameList = []
        data.forEach(cur => {
          if (cur.__config__.tag === 'Subform') {
              tempObj.tableNames.push(cur.__vModel__)
              cur.__config__.children[0].__config__.children.forEach(child => {
                  fieldNameList.push(child.__vModel__)
                  child.disabled =true
              })
          }
        })
        const tableValueMap = new Map()
        if(tempObj.tableNames.length > 0) { //// 是否存在子表单
            if(this.toView){  //从表单管理页面 查看 点击过来
                  let ListChild = JSON.parse(window.sessionStorage.getItem('childList'))
                  let childArr = []
                  tempObj.tableNames.map((item) => {
                    childArr.push(
                      {
                        tableName: item,
                        data: JSON.parse(ListChild&&ListChild[item])
                      }
                    )
                  })
                    // 子表单塞值
                    childArr.forEach(obj => {
                        obj.data.forEach(item => {
                            const keys = Object.keys(item)
                            for (let a = keys.length - 1; a >= 0 ; a--) {
                                const ele = keys[a]
                                if (!fieldNameList.includes(ele)) {
                                    delete item[ele]
                                }
                                if (fieldNameList.includes(ele)) {
                                    // 根据存储值换相应值(第二个参数'format'，暂时无法获取，format代替，问题未处理)
                                    item[ele] = this.setFormatValue(item[ele], 'format', this.tableTagIconsMap.get(ele)?.tag, this.tableTagIconsMap.get(ele)?.option,this.tableTagIconsMap.get(ele)?.dataType)
                                }
                            }
                            item.showComp = true
                        })
                        tableValueMap.set(obj.tableName, obj.data)
                    })
                    this.detailForm.fields.forEach(cur => {
                        if (cur.__config__.tag === 'Subform') {
                            cur.tableData = tableValueMap.get(cur.__vModel__)
                        }
                    })
                }else{
                tempObj.id = this.formRecordIdList[tab.index]
                tempObj.versionId = this.formRecordVersionList[tab.index]
                // 调用接口去查询相关子表单的数据
                await getChildListData(tempObj).then(resp => {
                  if (resp.code === 0) {
                      // 子表单塞值
                      resp.data.forEach(obj => {
                          obj.data.forEach(item => {
                              const keys = Object.keys(item)
                              for (let a = keys.length - 1; a >= 0 ; a--) {
                                  const ele = keys[a]
                                  if (!fieldNameList.includes(ele)) {
                                      delete item[ele]
                                  }
                                  if (fieldNameList.includes(ele)) {
                                      // 根据存储值换相应值(第二个参数'format'，暂时无法获取，format代替，问题未处理)
                                      item[ele] = this.setFormatValue(item[ele], 'format', this.tableTagIconsMap.get(ele)?.tag, this.tableTagIconsMap.get(ele)?.option,this.tableTagIconsMap.get(ele)?.dataType)
                                  }
                              }
                              item.showComp = true
                          })
                          tableValueMap.set(obj.tableName, obj.data)
                      })
                      data.forEach(cur => {
                          if (cur.__config__.tag === 'Subform') {
                              cur.tableData = tableValueMap.get(cur.__vModel__)
                          }
                      })
                      this.showTabs = true
                  }
              })
            }
          }

          if (panelType === 'tree-list') {
              const res = await getListData({
                  tableName: tableName,
                  dataType: 'all'
              })
              let tempTableData = []
              if (childrenParams && parentParams) {
                  tempTableData = this.handleTreeFmt(res.data.records, 'data_id', parentParams) || []
              }
              this.makeTreeList(tempTableData, childrenParams)
            
              // 设置表单的值
              data.forEach(item => {
                  let  val = this.processInstance.formVariablesList[tab.index][item.__vModel__]
                  if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(item.__config__.tag)) {
                    item.pageFlag = 'edit'
                  }
                  item.__config__.defaultValue = this.setFormatValue(val, item.format, item.__config__.tagIcon, item.options,item.dataType)
                  if (item.__vModel__ === parentParams) {
                      if (item.options) {
                          item.options = []
                      }
                      item.options = []
                      item.options = [...tempTableData]
                  }
              });
          } else {
              data.forEach(item => {
                let  val = this.processInstance.formVariablesList[tab.index][item.__vModel__]
                item.__config__.defaultValue = this.setFormatValue(val, item.format, item.__config__.tagIcon, item.options,item.dataType)
                if(item.__config__.tagIcon=== 'coding'){
                  // value = item.__config__.defaultValue
                  item.options=[{
                    label: item.__config__.defaultValue,
                    value:item.__config__.defaultValue
                  }]
                  this.codeReshow = {
                    label: item.__config__.defaultValue,
                    value:item.__config__.defaultValue
                  }
                }
            });
          }
            setTimeout(()=>{
                this.showForm = true
            },300)
    },
    changeRejection(val) { // 驳回指定节点 -- 返回方式只有按流程图执行
      if(val == 3){
        this.returnBtn.form.returnMethod = 1
      }
    },
    getTagIconsList(data,value) {
      if(data.__config__.tag === 'el-tabs' || data.__config__.tag === 'Steps'){
        data.__config__.children.map((c) => {
          if(c.__config__.tagIcon == 'row'){
            c.__config__.children.map((m) => {
              this.getTagIconsList(m,value)
            })
          }
        })
      }else{
        let tag = data.__config__.tagIcon
        let val = value[data.__vModel__]
        if(tag === 'cascader' || tag === 'checkbox' ){  //级联
              if (Array.isArray(val)) {
                  val = val.map((item) => {
                    return Number(item)
                  });
              } else {
                  val = val.split(',').map((item) => {
                    return Number(item)
                  });
              }
            }
            else if (tag === 'time-range' || tag === 'date-range'){
                val = val.split(',')
            }
            else  if (tag === 'radio' || tag === 'select' || tag === 'coding') {
                 val = Number(val)
              }
             else if (tag === 'upload') {
                if (typeof val === 'string') {
                    val = JSON.parse(val)
                }
              }
           else if (tag === 'switch') {
             val = val === 'true' ? true : false
            }
            data.__config__.defaultValue = val
      }
    },
  getTagIcons(data) {
      if(data.__config__.tag === 'el-tabs' || data.__config__.tag === 'Steps'){
        data.__config__.children.map((c) => {
          if(c.__config__.tagIcon == 'row'){
            c.__config__.children.map((m) => {
              this.getTagIcons(m)
            })
          }
        })
      }else{
        let tag = data.__config__.tagIcon
        let val = this.processInstance.formVariables[data.__vModel__]
        if(tag === 'cascader' || tag === 'checkbox' ){  //级联
              if (Array.isArray(val)) {
                  val = val.map((item) => {
                    return Number(item)
                  });
              } else {
                  val = val.split(',').map((item) => {
                    return Number(item)
                  });
              }
            }
            else if (tag === 'time-range' || tag === 'date-range'){
                val = val.split(',')
            }
            else  if (tag === 'radio' || tag === 'select') {
                 val = Number(val)
              }
             else if (tag === 'upload') {
                if (typeof val === 'string') {
                    val = JSON.parse(val)
                }
              }
           else if (tag === 'switch') {
             val = val === 'true' ? true : false
            }
            data.__config__.defaultValue = val
      }
    },
  verifySuffix(fileName) {
    let suffix = `(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg)`
    let regular = new RegExp(`.*\.${suffix}`)
    return regular.test(fileName)
  },
    /** 获得流程实例 */
    async getDetail() {
        // 获得流程实例相关
        this.processInstanceLoading = true;
        if(this.idList && this.idList.length > 0){ //批量审批
            await getBatchApprovalDetail(this.idList).then(async response => {
                if(response.code === 0){
                if (!response.data) {
                    this.$message.error('查询不到流程信息！');
                    return;
                    }
                    let exchangeMenuData = JSON.parse(JSON.stringify(response.data.formVariablesList));
                    this.exchangeobj = exchangeMenuData[0];
                    if(exchangeMenuData[0].manager_id && exchangeMenuData[0].newMenuId){
                      this.showexchange = true;
                      this.processInstanceLoadingExchange = true;
                      this.getExchangeMenuData(exchangeMenuData);
                    }
                    // 设置流程信息
                    this.processInstance = response.data;
                    this.dataList = []
                    this.activeNameList ="0"
                    this.idListbyDetail = response.data.idList
                    // // 设置表单信息
                    // if (this.processInstance.processDefinition.formType === 10) {
                    this.processInstance.processDefinition.formFieldsList && this.processInstance.processDefinition.formFieldsList.forEach((item,index)=> {
                        this.dataList.push({
                        ...JSON.parse(this.processInstance.processDefinition.formConf),
                            disabled: this.editRow ? false : true, // 表单禁用
                            formBtns: this.editRow ? true : false, // 按钮隐藏
                            fields: item?decodeFields(item):[]
                        })
                    })
                    const data =this.dataList[0].fields
                    const {panelType, childrenParams, parentParams, tableName} = this.$route.query
                    const tempObj = {}
                    tempObj.tableNames = []
                      // 存储所有子表单的字段name
                    const fieldNameList = []
                    data.forEach(cur => {
                      if (cur.__config__.tag === 'Subform') {
                          tempObj.tableNames.push(cur.__vModel__)
                          cur.__config__.children[0].__config__.children.forEach(child => {
                              fieldNameList.push(child.__vModel__)
                              child.disabled = true
                          })
                      }
                    })
                    const tableValueMap = new Map()
                    if(tempObj.tableNames.length > 0) { //// 是否存在子表单
                        tempObj.id = this.formRecordIdList[0]
                        tempObj.versionId = this.formRecordVersionList[0]
                          // 调用接口去查询相关子表单的数据
                        await getChildListData(tempObj).then(resp => {
                            if (resp.code === 0) {
                                // 子表单塞值
                                resp.data.forEach(obj => {
                                    obj.data.forEach(item => {
                                        const keys = Object.keys(item)
                                        for (let a = keys.length - 1; a >= 0 ; a--) {
                                            const ele = keys[a]
                                            if (!fieldNameList.includes(ele)) {
                                                delete item[ele]
                                            }
                                            if (fieldNameList.includes(ele)) {
                                                // 根据存储值换相应值(第二个参数'format'，暂时无法获取，format代替，问题未处理)
                                                item[ele] = this.setFormatValue(item[ele], 'format', this.tableTagIconsMap.get(ele)?.tag, this.tableTagIconsMap.get(ele)?.option,this.tableTagIconsMap.get(ele)?.dataType)
                                            }
                                        }
                                        item.showComp = true
                                    })
                                    tableValueMap.set(obj.tableName, obj.data)
                                })
                                data.forEach(cur => {
                                    if (cur.__config__.tag === 'Subform') {
                                        cur.tableData = tableValueMap.get(cur.__vModel__)
                                    }
                                })
                            }
                        })
                      }

                      if (panelType === 'tree-list') {
                          const res = await getListData({
                              tableName: tableName,
                              dataType: 'all'
                          })
                          let tempTableData = []
                          if (childrenParams && parentParams) {
                              tempTableData = this.handleTreeFmt(res.data.records, 'data_id', parentParams) || []
                          }
                          this.makeTreeList(tempTableData, childrenParams)
                        
                          // 设置表单的值
                          data.forEach(item => {
                              let  val = this.processInstance.formVariables[item.__vModel__]
                              if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(item.__config__.tag)) {
                                item.pageFlag = 'edit'
                              }
                              item.__config__.defaultValue = this.setFormatValue(val, item.format, item.__config__.tagIcon, item.options,item.dataType)
                              if (item.__vModel__ === parentParams) {
                                  if (item.options) {
                                      item.options = []
                                  }
                                  item.options = []
                                  item.options = [...tempTableData]
                              }
                              // this.getTagIcons(item)
                          });
                      } else {
                          // 设置表单的值
                            data.forEach(item => {
                              let  val = this.processInstance.formVariables[item.__vModel__]
                              if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(item.__config__.tag)) {
                                item.pageFlag = 'edit'
                              }
                              item.__config__.defaultValue = this.setFormatValue(val, item.format, item.__config__.tagIcon, item.options,item.dataType)
                              if(item.__config__.tagIcon=== 'coding'){
                                // value = item.__config__.defaultValue
                                item.options=[{
                                  label: item.__config__.defaultValue,
                                  value:item.__config__.defaultValue
                                }]
                                this.codeReshow = {
                                  label: item.__config__.defaultValue,
                                  value:item.__config__.defaultValue
                                }
                              }
                               // this.getTagIconsList(item,this.processInstance.formVariablesList[0])
                            });
                      }
                    
                    // 加载流程图
                    getProcessDefinitionBpmnXML(this.processInstance.processDefinition.id,this.processInstance.id).then(response => {
                      this.bpmnXML = response.data.bpmnXml
                      this.buttonList = response.data.bpmnButton?.button
                      this.carbonFlag = response.data.bpmnButton?.carbon?.isChecked //是否抄送
                      this.infoFlag = response.data.bpmnButton?.carbon?.isShow //是否显示附加信息
                    });


                    // 加载活动列表
                    getActivityList({
                    processInstanceId: this.processInstance.id
                    }).then(response => {
                    this.activityList = response.data;
                    });
                    this.showForm = true

                    // 取消加载中
                    this.processInstanceLoading = false;

                }
            })
        }else{
            const response = await getProcessInstance(this.id)
            if (!response.data) {
                this.$message.error('查询不到流程信息！');
                return;
            }
            let exchangeMenuData = JSON.parse(JSON.stringify(response.data.formVariables));
            this.exchangeobj = exchangeMenuData;
            if(exchangeMenuData.manager_id && exchangeMenuData.newMenuId){
              this.showexchange = true;
              this.processInstanceLoadingExchange = true;
              this.getExchangeMenuData(exchangeMenuData);
            }
            // 设置流程信息
            this.processInstance = response.data;
            this.detailForm = {
                ...JSON.parse(this.processInstance.processDefinition.formConf),
                disabled: this.editRow ? false : true, // 表单禁用
                formBtns: this.editRow ? true : false, // 按钮隐藏
                fields: decodeFields(this.processInstance.processDefinition.formFields || [])
            }
            const {panelType, childrenParams, parentParams, tableName} = this.$route.query
            const tempObj = {}
            tempObj.tableNames = []
              // 存储所有子表单的字段name
            const fieldNameList = []
            this.detailForm.fields.forEach(cur => {
              if (cur.__config__.tag === 'Subform') {
                  tempObj.tableNames.push(cur.__vModel__)
                  cur.__config__.children[0].__config__.children.forEach(child => {
                      child.disabled = true
                      fieldNameList.push(child.__vModel__)
                  })
              }
            })
             const tableValueMap = new Map()
            if(tempObj.tableNames.length > 0) { //// 是否存在子表单
                if(this.toView){  //从表单管理页面 查看 点击过来
                  let ListChild = JSON.parse(window.sessionStorage.getItem('childList'))
                    // 子表单塞值
                    ListChild?.childTables && ListChild?.childTables.forEach(obj => {
                      let data =Array.isArray(obj.data)?obj.data: JSON.parse(obj.data)
                        data && data.forEach(item => {
                            const keys = Object.keys(item)
                            for (let a = keys.length - 1; a >= 0 ; a--) {
                                const ele = keys[a]
                                if (!fieldNameList.includes(ele)) {
                                    delete item[ele]
                                }
                                if (fieldNameList.includes(ele)) {
                                    // 根据存储值换相应值(第二个参数'format'，暂时无法获取，format代替，问题未处理)
                                    item[ele] = this.setFormatValue(item[ele], 'format', this.tableTagIconsMap.get(ele)?.tag, this.tableTagIconsMap.get(ele)?.option,this.tableTagIconsMap.get(ele)?.dataType)
                                }
                            }
                            item.showComp = true
                        })
                        tableValueMap.set(obj.tableName, data)
                    })
                    if( ListChild?.childTables && ListChild?.childTables){
                      this.detailForm.fields.forEach(cur => {
                        if (cur.__config__.tag === 'Subform') {
                            cur.tableData = tableValueMap.get(cur.__vModel__)
                        }
                    })
                  }
                }else{
                  tempObj.id = this.tableId
                  tempObj.versionId = this.versionId
                    // 调用接口去查询相关子表单的数据
                  await getChildListData(tempObj).then(resp => {
                      if (resp.code === 0) {
                          // 子表单塞值
                          resp.data.forEach(obj => {
                              obj.data.forEach(item => {
                                  const keys = Object.keys(item)
                                  for (let a = keys.length - 1; a >= 0 ; a--) {
                                      const ele = keys[a]
                                      if (!fieldNameList.includes(ele)) {
                                          delete item[ele]
                                      }
                                      if (fieldNameList.includes(ele)) {
                                          // 根据存储值换相应值(第二个参数'format'，暂时无法获取，format代替，问题未处理)
                                          item[ele] = this.setFormatValue(item[ele], 'format', this.tableTagIconsMap.get(ele)?.tag, this.tableTagIconsMap.get(ele)?.option,this.tableTagIconsMap.get(ele)?.dataType)
                                      }
                                  }
                                  item.showComp = true
                              })
                              tableValueMap.set(obj.tableName, obj.data)
                          })
                          this.detailForm.fields.forEach(cur => {
                              if (cur.__config__.tag === 'Subform') {
                                  cur.tableData = tableValueMap.get(cur.__vModel__)
                              }
                          })
                      }
                  })
                }
              }
              if (panelType === 'tree-list') {
                const res = await getListData({
                    tableName: tableName,
                    dataType: 'all'
                })
                let tempTableData = []
                if (childrenParams && parentParams) {
                    tempTableData = this.handleTreeFmt(res.data.records, 'data_id', parentParams) || []
                }
                this.makeTreeList(tempTableData, childrenParams)
              
              
                // 设置表单的值
                this.detailForm.fields.forEach(item => {
                    let  val = this.processInstance.formVariables[item.__vModel__]
                    if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(item.__config__.tag)) {
                        item.pageFlag = 'edit'
                    }
                    item.__config__.defaultValue = this.setFormatValue(val, item.format, item.__config__.tagIcon, item.options,item.dataType)
                    if (item.__vModel__ === parentParams) {
                        if (item.options) {
                            item.options = []
                        }
                        item.options = []
                        item.options = [...tempTableData]
                    }
                    // this.getTagIcons(item)
                });
            } else {
                // 设置表单的值
                this.detailForm.fields.forEach(item => {
                    let  val = this.processInstance.formVariables[item.__vModel__]
                    if(item.__config__.tag === 'el-card'){ //如果是卡片布局
                      item.__config__.children && item.__config__.children.map((i) => {
                        i.__config__.children.map((data) => {
                          let value = this.processInstance.formVariables[data.__vModel__]
                        data.__config__.defaultValue = this.setFormatValue(value, data.format, data.__config__.tagIcon, data.options,data.dataType)
                        })
                      })
                     
                    }else{
                      item.__config__.defaultValue = this.setFormatValue(val, item.format, item.__config__.tagIcon, item.options,item.dataType)
                    }
                    // this.getTagIcons(item)
                    if (['UsersSelector', 'DepartmentSelection', 'PostSelection'].includes(item.__config__.tag)) {
                        item.pageFlag = 'edit'
                    }

                    if(item.__config__.tagIcon=== 'coding'){
                      // value = item.__config__.defaultValue
                      item.options=[{
                        label: item.__config__.defaultValue,
                        value:item.__config__.defaultValue
                      }]
                      this.codeReshow = {
                        label: item.__config__.defaultValue,
                        value:item.__config__.defaultValue
                      }
                    }
                });
            }
            
            // 加载流程图
            getProcessDefinitionBpmnXML(this.processInstance.processDefinition.id,this.processInstance.id).then(response => {
                this.bpmnXML = response.data.bpmnXml
                this.buttonList = response.data.bpmnButton?.button
                this.carbonFlag = response.data.bpmnButton?.carbon?.isChecked //是否抄送
                this.infoFlag = response.data.bpmnButton?.carbon?.isShow //是否显示附加信息
            });

            // 加载活动列表
            getActivityList({
                processInstanceId: this.processInstance.id
            }).then(response => {
                this.activityList = response.data;
            });
            // 取消加载中
            this.processInstanceLoading = false;
        }
        // 获得流程任务列表（审批记录）
        this.tasksLoad = true;
        this.runningTasks = [];
        this.auditForms = [];
        await getTaskListByProcessInstanceId(this.id).then(response => {
            // 审批记录
            this.tasks = response.data;

            // 排序，将未完成的排在前面，已完成的排在后面；
            this.tasks.sort((a, b) => {
            // 有已完成的情况，按照完成时间倒序
            if (a.endTime && b.endTime) {
                return b.endTime - a.endTime;
            } else if (a.endTime) {
                return 1;
            } else if (b.endTime) {
                return -1;
                // 都是未完成，按照创建时间倒序
            } else {
                return b.createTime - a.createTime;
            }
            });

            // 需要审核的记录
            const userId = store.getters.userId;
            this.userId = userId
            this.tasks.forEach(task => {
            task.imageList = []
            task.file = []
            task.fileList && task.fileList.map((_) => {
               if(this.verifySuffix(_.name)){
                  task.imageList.push(_)
               }else{
                 task.file.push(_)
               }
            })
            if (task.result !== 1) { // 只有待处理才需要
                return;
            }
            if (!task.assigneeUser || task.assigneeUser.id !== userId) { // 自己不是处理人
                return;
            }
            this.runningTasks.push({...task});
            this.auditForms.push({
                reason: ''
            })
            });

            // 取消加载中
            this.tasksLoad = false;
        });
        await this.$nextTick(()=>{
         this.timekey = Date.now()
        })
    },
    //时间戳转日期时间
    getDateTime(time) {
        if (!time) return ''
        let date = new Date(time)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
    },
    //判断是否是json
      isJson(str) {
        if (typeof (str) === 'string') {
          try {
            var obj = JSON.parse(str)
            if (typeof (obj) === 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
    //将数据库存储类型转为组件数据类型
    setFormatValue(data, format, tag, options, dataType) {
        if (!data) { //空数据
            return data
        }
        if (format === 'datetime') {
            return this.getDateTime(data)
        }
        if (tag === 'upload') {
            if (this.isJson(data)) {
                return JSON.parse(data)
            } else {
                return []
            }
        }
        if (basicTypes.includes(tag)) {
            return data
        }
        if (['time-range','date-range','user','post','depart'].includes(tag)) {
            return (data+ '').split(',')
        }
        if (tag === 'switch') {
            if (data === options[0].toString()) {
                data = options[0]
            } else if (data === options[1].toString()){
                data = options[1]
            }
            return data
        }
        if (tag === 'radio' || tag === 'select' ||tag === 'coding') {
            let option = options.filter((item) => {
                return item.value.toString() === data || item.label.toString() === data
            })
            return option.length > 0 ? option[0].value : data
        }
        if (tag === 'checkbox') {
            let keys = data.split(',')
            let newKeys = keys.map((item,index) => {
                let option = options.filter((opt) => {
                    return opt.value.toString() === item || opt.label.toString() === item
                })
                return option.length > 0 ? option[0].value : item
            })
            return newKeys
        }
        if (tag === 'cascader'|| tag === 'tree-table') {
            let tempkeys = (data + '').split(',')
            let str = []
            let index = 0
            tempkeys.length > 0 && this.getValueByKey(options, tempkeys, index, str)
            if(tag === 'cascader' && dataType === 'dynamic'){
                str = tempkeys;
            }
            if(tag === 'tree-table' && !str.length){
                str = tempkeys;
            }
            return str
        }
        return data
    },
    //根据key值获取value
    getValueByKey(options, key, index, str) {
        options && options.length > 0 && options.forEach((item) => {
            if (item.value + '' === key[index] || item.label + '' === key[index]) {
                str.push(item.value)
                index++
                item?.children && index < key.length && this.getValueByKey(item.children, key, index, str)
                return true
            }
        })
    },
    // 处理层级关系
    makeTreeList (children, childrenParams) {
        for (let a = 0; a < children.length; a++) {
            const obj = children[a]
            const keys = Object.keys(obj)
            let str = obj['data_id']?obj['data_id']:obj.id
            keys.forEach(key => {
                if (childrenParams === key) {
                    obj.label = obj[key]
                    obj.value = str
                }
                if (key !== 'children') {
                    delete obj[key]
                }
            })
            obj.children?.length > 0 && this.makeTreeList(obj.children, childrenParams)
        }
    },
    handleTreeFmt(data, id, parentId) {
        id = id || 'id'
        parentId = parentId || 'parentId'
        //对源数据深度克隆
        const cloneData = JSON.parse(JSON.stringify(data))
        //循环所有项
        const treeData = cloneData.filter(father => {
            let branchArr = cloneData.filter(child => {
            //返回每一项的子级数组
            return father[id] + '' == child[parentId] + ''
            });
            branchArr.length > 0 ? father.children = branchArr : '';
            //返回第一层
            return father[parentId] + '' == '' ||father[parentId] === 0;
        });
        return treeData !== '' ? treeData : data;
      },
    /** 处理选择流程的按钮操作 **/
    handleSelect(row) {
      // 设置选择的流程
      this.selectProcessInstance = row;

      // 流程表单
      if (row.formId) {
        // 设置对应的表单
        this.detailForm = {
          ...JSON.parse(row.formConf),
          fields: decodeFields(row.formFields)
        }
      } else if (row.formCustomCreatePath) {
        this.$router.push({ path: row.formCustomCreatePath});
        // 这里暂时无需加载流程图，因为跳出到另外个 Tab；
      }
    },
    /** 提交按钮 */
    submitForm(params) {
      if (!params) {
        return;
      }
        // 提交表单，创建流程
      const variables = params.values;
      if(this.editRow){  // 我的任务编辑
        const formJsonData = JSON.parse(this.editRow.formJsonData)
        formJsonData.data?.map((item) => {
          item.value =  params.values[item.name]
          item.type =  item.format
        })
        const data = {
          ...formJsonData,
          dataId: this.editRow.formId,
        }
        updata(data).then((res) => {
          this.$message.success('修改成功')
            // 关闭当前窗口
          this.$tab.closeOpenPage();
          this.$router.go(-1);
        })
      }else{
          // 设置表单禁用
        const conf = params.conf;
        conf.disabled = true; // 表单禁用
        conf.formBtns = false; // 按钮隐藏
        createProcessInstance({
          processDefinitionId: this.selectProcessInstance.id,
          variables: variables
        }).then(response => {
          this.$modal.msgSuccess("发起流程成功");
          // 关闭当前窗口
          this.$tab.closeOpenPage();
          this.$router.go(-1);
        }).catch(() => {
          conf.disabled = false; // 表单开启
          conf.formBtns = true; // 按钮展示
        })
      }
    },
    getDateStar(ms) {
      return getDate(ms);
    },
    getTimelineItemIcon(item) {
      if (item.result === 1) {
        return 'el-icon-time';
      }
      if (item.result === 2) {
        return 'el-icon-check';
      }
      if (item.result === 3) {
        return 'el-icon-close';
      }
      if (item.result === 4) {
        return 'el-icon-remove-outline';
      }
      return '';
    },
    getTimelineItemType(item) {
      if (item.result === 1) {
        return 'primary';
      }
      if (item.result === 2) {
        return 'success';
      }
      if (item.result === 3) {
        return 'danger';
      }
      if (item.result === 4) {
        return 'info';
      }
      return '';
    },
    /** 处理审批通过和不通过的操作 */
    handleAudit(task, pass) {
      this.tagsList.length > 0 ? this.showFlag = false : this.showFlag = true
      const index = this.runningTasks.indexOf(task);
      this.$refs['form' + index][0].validate(valid => {
        if (!valid) {
          return;
        }
       
        if(this.idList && this.idList.length > 0){ //批量审批
         //抄送
            let arr = []
            this.tagsList && this.tagsList.map((_) => {
                arr.push(_.id)
            })
            const copyData = {
              taskId: task.id,
              processInstanceId: this.processInstance.id,
              userIds: arr,
              processInstanceIdList: this.idList,
              taskIdList: this.idListbyDetail,
            }
            if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
              batchCarbonCopy(copyData).then((res) =>{ })
            }

          let data = {
            idList: this.idListbyDetail,
            reason: this.auditForms[index].reason,
            fileList: this.fileDocList   //文件附件
          }
          if (pass) {  //通过
              batchApprove(data).then(response => {
                this.tagsList = []
                this.fileList = []
                this.fileDocList = []
                this.checked = false
                this.$modal.msgSuccess("批量审批通过成功！");
                this.getDetail(); // 获得最新详情
              })
          }else{
            // 不通过
            batchReject(data).then(response => {
              this.$modal.msgSuccess("审批不通过成功！");
              this.getDetail(); // 获得最新详情
            });
          }
        }else{
           //抄送
            let arr = []
            this.tagsList && this.tagsList.map((_) => {
                arr.push(_.id)
            })
            const copyData = {
              taskId: task.id,
              processInstanceId: this.processInstance.id,
              userIds: arr,
            }
            if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
              getCarbonCopy(copyData).then((res) =>{ })
            }
            const data = {
            id: task.id,
            reason: this.auditForms[index].reason,
            fileList: this.fileDocList   //文件附件
          }
          if (pass) {
            approveTask(data).then(response => {
              this.tagsList = []
              this.fileList = []
              this.fileDocList = []
              this.checked = false
              this.$modal.msgSuccess("审批通过成功！");
              this.getDetail(); // 获得最新详情
            });
          } else {
            rejectTask(data).then(response => {
              this.$modal.msgSuccess("审批不通过成功！");
              this.getDetail(); // 获得最新详情
            });
          }
        }
        
      });
    },
    /** 处理转派审批人 */
    handleUpdateAssignee(task) {
      this.tagsList.length > 0 ? this.showFlag = false : this.showFlag = true
      const index = this.runningTasks.indexOf(task);
      this.$refs['form' + index][0].validate(valid => {
        if (!valid) {
          return;
        }
        if(this.checked && this.tagsList.length == 0){
          return;
        }
        this.reason = this.auditForms[index].reason
        // 设置表单
        this.resetUpdateAssigneeForm();
        this.updateAssignee.form.id = task.id;
        // 设置为打开
        this.updateAssignee.open = true;
      })
     
    },
    /** 提交转派审批人 */
    submitUpdateAssigneeForm() {
      this.$refs['updateAssigneeForm'].validate(valid => {
        if (!valid) {
          return;
        }
        if(this.idList && this.idList.length > 0){ //批量审批
            //抄送
          let arr = []
          this.tagsList && this.tagsList.map((_) => {
              arr.push(_.id)
          })
          const copyData = {
            taskId: this.updateAssignee.form.id,
            processInstanceId: this.processInstance.id,
            userIds: arr,
            processInstanceIdList: this.idList,
            taskIdList: this.idListbyDetail,
          }
           if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
              batchCarbonCopy(copyData).then((res) =>{ })
            }
          const data = {
            idList: this.idListbyDetail,
            ...this.updateAssignee.form,
            reason: this.reason,
            fileList: this.fileDocList   //文件附件
          }
          // if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
          //   getCarbonCopy(copyData).then((res) =>{ })
          // }
          batchAssignee(data).then(response => {
            this.$modal.msgSuccess("转派任务成功！");
            this.tagsList = []
            this.checked = false
            this.fileList = []
            this.fileDocList = []
            this.updateAssignee.open = false;
            this.getDetail(); // 获得最新详情
          });
        }else{
            //抄送
          let arr = []
          this.tagsList && this.tagsList.map((_) => {
              arr.push(_.id)
          })
          const copyData = {
            taskId: this.updateAssignee.form.id,
            processInstanceId: this.processInstance.id,
            userIds: arr,
          
          }
          const data = {
            ...this.updateAssignee.form,
            reason: this.reason,
            fileList: this.fileDocList   //文件附件
          }
          if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
            getCarbonCopy(copyData).then((res) =>{ })
          }
          updateTaskAssignee(data).then(response => {
            this.$modal.msgSuccess("转派任务成功！");
            this.tagsList = []
            this.checked = false
            this.fileList = []
            this.fileDocList = []
            this.updateAssignee.open = false;
            this.getDetail(); // 获得最新详情
          });
        }
      });
    },
    /** 取消转派审批人 */
    cancelUpdateAssigneeForm() {
      this.updateAssignee.open = false;
      this.resetUpdateAssigneeForm();
    },
    /** 重置转派审批人 */
    resetUpdateAssigneeForm() {
      this.updateAssignee.form = {
        id: undefined,
        assigneeUserId: undefined,
      };
      this.resetForm("updateAssigneeForm");
    },
    /** 处理审批退回的操作 */
    handleDelegate(task) {
      this.$modal.msgError("暂不支持【委派】功能，可以使用【转派】替代！");
    },
    /** 退回 */
    handleBack(task) {
      this.tagsList.length > 0 ? this.showFlag = false : this.showFlag = true
      const index = this.runningTasks.indexOf(task);
      this.$refs['form' + index][0].validate(valid => {
        if (!valid) {
          return;
        }
        if(this.checked && this.tagsList.length == 0){
          return;
        }
        this.reason = this.auditForms[index].reason
         // 设置表单
        this.resetReturnBtnForm();
        this.returnBtn.form.id = task.id;
        // 设置为打开
        if(!this.showexchange){
        this.returnBtn.open = true;
        }else{
          const data = {
    reason: this.reason,
    fileList: this.fileDocList,   //文件附件
    position: this.returnBtn.form.rejection == 1 ? 'start': 'last',
    type: "BH", // 驳回的方式
    distFlowElementId: this.returnBtn.form.distFlowElementId,
    // message: this.returnBtn.form.message,
    userId: this.userId, // 审批用户的id
    taskId: this.returnBtn.form.id,   // 任务id
  }
   if(this.idList && this.idList.length > 0){
    data.taskIdList = this.idListbyDetail;
batchDoBackDist(data).then((res) => {
    this.$modal.msgSuccess("驳回成功！");
    this.tagsList = []
    this.fileList = []
    this.fileDocList = []
    this.checked = false
    this.returnBtn.open = false;
    this.getDetail(); // 获得最新详情
  })
   }else{
    doBackDist(data).then((res) => {
    this.$modal.msgSuccess("驳回成功！");
    this.tagsList = []
    this.fileList = []
    this.fileDocList = []
    this.checked = false
    this.returnBtn.open = false;
    this.getDetail(); // 获得最新详情
  })
   }
  
        }
        getNodeList(task.id).then((res) => {
            this.nodeList = res.data;
        })
      })
    },
      /** 重置退回 */
    resetReturnBtnForm() {
      this.returnBtn.form = {
        rejection: 1,
        returnMethod: 1,
        distFlowElementId: undefined,
        suggestion: undefined
      };
      this.resetForm("returnBtnForm");
    },
    /* 驳回提交 */
    submitReturnBtnForm() {
      this.$refs['returnBtnForm'].validate(valid => {
        if (!valid) {
          return;
        }
        if(this.idList && this.idList.length > 0){ //批量审批
            console.log(this.returnBtn.form.rejection,'kkkk')
            if(this.returnBtn.form.rejection == 3){ // 驳回到指定节点
                this.$message.warning('批量删除不能驳回到指定节点')
                return;
            }
                //抄送
          let arr = []
          this.tagsList && this.tagsList.map((_) => {
              arr.push(_.id)
          })
          const copyData = {
            taskId: this.returnBtn.form.id,
            processInstanceId: this.processInstance.id,
            userIds: arr,
            processInstanceIdList: this.idList,
            taskIdList: this.idListbyDetail,
          }
           if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
              batchCarbonCopy(copyData).then((res) =>{ })
            }
          const data = {
            reason: this.reason,
            fileList: this.fileDocList,   //文件附件
            position: this.returnBtn.form.rejection == 1 ? 'start': 'last',
            type: "BH", // 驳回的方式
            distFlowElementId: this.returnBtn.form.distFlowElementId,
            // message: this.returnBtn.form.message,
            userId: this.userId, // 审批用户的id
            taskId: this.returnBtn.form.id,   // 任务id
            taskIdList: this.idListbyDetail,
          }
          batchDoBackDist(data).then((res) => {
            this.$modal.msgSuccess("驳回成功！");
            this.tagsList = []
            this.fileList = []
            this.fileDocList = []
            this.checked = false
            this.returnBtn.open = false;
            this.getDetail(); // 获得最新详情
          })
        }else{
             //抄送
        let arr = []
        this.tagsList && this.tagsList.map((_) => {
            arr.push(_.id)
        })
        const copyData = {
           taskId: this.returnBtn.form.id,
           processInstanceId: this.processInstance.id,
           userIds: arr,
        }
        if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
           getCarbonCopy(copyData).then((res) =>{ })
        }
        if(this.returnBtn.form.rejection == 3){ // 驳回到指定节点
           const data = {
            reason: this.reason,
            fileList: this.fileDocList,   //文件附件
            // processInstanceId: this.processInstance.id,
            type: "BH", // 驳回的方式
            distFlowElementId: this.returnBtn.form.distFlowElementId,
            // message: this.returnBtn.form.message,
            userId: this.userId, // 审批用户的id
            taskId: this.returnBtn.form.id   // 任务id
          }
          doBack(data).then((res) => {
            this.$modal.msgSuccess("驳回成功！");
            this.tagsList = []
            this.fileList = []
            this.fileDocList = []
            this.checked = false
            this.returnBtn.open = false;
            this.getDetail(); // 获得最新详情
          })
        }else{ // 驳回发起人，驳回上一步
          const data = {
            reason: this.reason,
            fileList: this.fileDocList,   //文件附件
            position: this.returnBtn.form.rejection == 1 ? 'start': 'last',
            type: "BH", // 驳回的方式
            distFlowElementId: this.returnBtn.form.distFlowElementId,
            // message: this.returnBtn.form.message,
            userId: this.userId, // 审批用户的id
            taskId: this.returnBtn.form.id   // 任务id
          }
          doBackDist(data).then((res) => {
            this.$modal.msgSuccess("驳回成功！");
            this.tagsList = []
            this.fileList = []
            this.fileDocList = []
            this.checked = false
            this.returnBtn.open = false;
            this.getDetail(); // 获得最新详情
          })
        }
        }
        
      });
    },
    cancelReturnBtnForm() {
      this.returnBtn.open = false;
      this.resetReturnBtnForm();
    },
    getExchangeMenuData(exchangeMenuData){
      if(!Array.isArray(exchangeMenuData)){
exchangeMenuData = [exchangeMenuData];
      }
      getAllListDataForm('catalog').then(res=>{
                 this.processInstanceLoadingExchange = false;
                  if(res.code===0){
                    let cur = res.data.records.filter(item=>{
                      return exchangeMenuData.some(s=>{
                        return item.data_id === s.dataId;
                    });
                    
                    });
                    cur.forEach(val=>{
                      exchangeMenuData.forEach(t=>{
                        if(val.data_id===t.dataId){
val.menu_id = t.newMenuId;
                    val.dept_id = t.approve_dept;
                        }
                      });
                      
                    });
                    
                    this.exchangeOriginData = cur;
                    this.exchangeMenuShow = true;
                  }
                }).catch(e=>{
                  this.processInstanceLoadingExchange = false;
                })
    },
  }
};
</script>

<style lang="scss">
.my-process-designer {
  height: calc(100vh - 200px);
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}
 .inputSelect{
  width: 100%;
  height: 36px;
  line-height: 2.3;
  background-color: #FFFFFF;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  padding: 0 15px;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
}
.ruleInput .el-form-item__label::before{
    content: "*";
    color: #ff4949;
    margin-right: 4px;
}
.noNull{
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: absolute;
    top: 100%;
    left: 0;
}
.fileTextCss{
    cursor: pointer;
    width: 35%;
    padding: 0 10px;
    display: inline-block;
    vertical-align: text-bottom;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    &:hover {
        color: #409EFF;
    }
}
.lineFilecss{
    padding: 3px 0;
}
.fileIcon{
    padding: 0 5px;
    cursor: pointer;
    &:hover {
        color: #409EFF;
    }
}
</style>
